package com.example.bookmanagement.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bookmanagement.common.AjaxResponse;
import com.example.bookmanagement.dto.BookQueryDTO;
import com.example.bookmanagement.entity.Book;
import com.example.bookmanagement.service.BookService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/books")
@Tag(name = "图书管理", description = "图书的增删改查操作")
@Slf4j
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping
    @Operation(summary = "分页查询图书列表，支持书名、作者、出版日期过滤")
    public AjaxResponse<IPage<Book>> getBooks(
            @Parameter(description = "当前页码，默认1", example = "1") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页记录数，默认10", example = "10") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "图书查询条件") BookQueryDTO queryDTO) {
        Page<Book> page = new Page<>(pageNum, pageSize);
        IPage<Book> bookPage = bookService.getBooksByPage(page, queryDTO);
        log.info("查询图书列表，条件：{}，结果：{}", queryDTO, JSON.toJSONString(bookPage));
        return AjaxResponse.success(bookPage);
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取图书信息")
    public AjaxResponse<Book> getBookById(@PathVariable Long id) {
        Optional<Book> bookOptional = bookService.getBookById(id);
        log.info("查询图书，ID：{}，结果：{}", id, JSON.toJSONString(bookOptional));
        if (bookOptional.isPresent()) {
            return AjaxResponse.success(bookOptional.get());
        } else {
            return AjaxResponse.error("图书不存在");
        }
    }

    @PostMapping("/add")
    @Operation(summary = "新增图书")
    public AjaxResponse<Book> saveBook(@RequestBody Book book) {
        Book savedBook = bookService.saveBook(book);
        log.info("新增图书，图书信息：{}", JSON.toJSONString(savedBook));
        return AjaxResponse.success(savedBook);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "根据ID删除图书")
    public AjaxResponse<Void> deleteBook(@PathVariable Long id) {
        bookService.deleteBook(id);
        return AjaxResponse.success(null);
    }

    @PutMapping("/{id}")
    @Operation(summary = "根据ID更新图书信息")
    public AjaxResponse<Book> updateBook(@PathVariable Long id, @RequestBody Book book) {
        Book updatedBook = bookService.updateBook(id, book);
        log.info("更新图书，ID：{}，图书信息：{}", id, JSON.toJSONString(updatedBook));
        return AjaxResponse.success(updatedBook);
    }
}